package cn.zmit.kuxi.request;



import java.io.File;
import java.io.FileNotFoundException;

import org.json.JSONObject;

import android.util.Log;

import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.loopj.android.http.RequestParams;

public class YBRRequest {
	String m_strRequestTag; // Tag to distinguish the request
	String m_strUrl; // The URL of the request
	AsyncHttpClient m_pHttpClient; // The async http client
	RequestParams m_pParams; // The parameters for request
	JSONObject m_pResponseJson; // The response json
	boolean m_bSilent; // If pop up error message when the request failed
	boolean m_bRequestCancelled; // YES when Cancel function is called
	boolean m_bSucceed; // YES if the request succeeds.
	YBRResponseHandler m_pResponseHandler; // The handler to deal with the
											// success/failure of the request

	public String getM_strRequestTag() {
		return m_strRequestTag;
	}

	public void setM_strRequestTag(String m_strRequestTag) {
		this.m_strRequestTag = m_strRequestTag;
	}

	public String getM_strUrl() {
		return m_strUrl;
	}

	public void setM_strUrl(String m_strUrl) {
		this.m_strUrl = m_strUrl;
	}

	public AsyncHttpClient getM_pHttpClient() {
		return m_pHttpClient;
	}

	public void setM_pHttpClient(AsyncHttpClient m_pHttpClient) {
		this.m_pHttpClient = m_pHttpClient;
	}

	public RequestParams getM_pParams() {
		return m_pParams;
	}

	public void setM_pParams(RequestParams m_pParams) {
		this.m_pParams = m_pParams;
	}

	public JSONObject getM_pResponseJson() {
		return m_pResponseJson;
	}

	public void setM_pResponseJson(JSONObject m_pResponseJson) {
		this.m_pResponseJson = m_pResponseJson;
	}

	public boolean isM_bSilent() {
		return m_bSilent;
	}

	public void setM_bSilent(boolean m_bSilent) {
		this.m_bSilent = m_bSilent;
	}

	public boolean isM_bRequestCancelled() {
		return m_bRequestCancelled;
	}

	public void setM_bRequestCancelled(boolean m_bRequestCancelled) {
		this.m_bRequestCancelled = m_bRequestCancelled;
	}

	public boolean isM_bSucceed() {
		return m_bSucceed;
	}

	public void setM_bSucceed(boolean m_bSucceed) {
		this.m_bSucceed = m_bSucceed;
	}

	public YBRResponseHandler getM_pResponseHandler() {
		return m_pResponseHandler;
	}

	public void setM_pResponseHandler(YBRResponseHandler m_pResponseHandler) {
		this.m_pResponseHandler = m_pResponseHandler;
	}

	JsonHttpResponseHandler pResponseHandler = new JsonHttpResponseHandler() {

		@Override
		public void onStart() {
			// TODO: Start
		}

		@Override
		public void onSuccess(int statusCode, org.apache.http.Header[] headers,
				JSONObject response) {

			if (m_bRequestCancelled) {
				Log.i("Request", "url=" + this.getRequestURI() + " cancelled");
				return;
			}
			try {
				if (response == null) {
					throw new Exception("服务器请求失败, 别灰心，再试试。");
				}

				Log.i("Request", "url=" + this.getRequestURI() + " response="
						+ response.toString());
				m_pResponseJson = response;

				int iStatus = m_pResponseJson.getInt("code");
				if (iStatus == 1) {
					// Succeed
					if (m_pResponseHandler != null)
						m_pResponseHandler.OnSuccess(YBRRequest.this);
				} else {
					throw new Exception(m_pResponseJson.getString("message"));
				}

				m_bSucceed = true;
			} catch (Exception e) {
				m_bSucceed = false;

				Log.i("Request", "url=" + this.getRequestURI() + " params="
						+ this.getRequestHeaders().toString() + " exception="
						+ e.getMessage());
				if (!m_bSilent && !e.getMessage().equals("请登录")) {
					// TODO: Show toast
					// U.ShowToast(MyApplication.getContext(), e.getMessage());
				}

				// If the fail reason is "没有登录", then we post this notification
				if (e.getMessage().equals("请登录")) {
					Log.i("BURequest", "Relogin");

					// TODO: Notify others not login
				}

				// Failed
				if (m_pResponseHandler != null)
					m_pResponseHandler.OnFailure(YBRRequest.this);
			}

		}

		@Override
		public void onFailure(int statusCode, org.apache.http.Header[] headers,
				java.lang.Throwable throwable, org.json.JSONObject errorResponse) {
			m_bSucceed = false;

			if (errorResponse != null)
				Log.i("Request", "errorResponse=" + errorResponse.toString());
			if (throwable != null)
				Log.i("Request", " error=" + throwable.toString());
			// If the request is cancelled, we do nothing
			if (m_bRequestCancelled)
				return;

			if (!m_bSilent) {
				Log.i("Request", "onFailure");

			}

			// Failed
			if (m_pResponseHandler != null)
				m_pResponseHandler.OnFailure(YBRRequest.this);
		}

		public void onFailure(int statusCode, org.apache.http.Header[] headers,
				String responseString, Throwable throwable) {
			m_pResponseHandler.OnFailure(YBRRequest.this);
		};

		public void onFailure(int statusCode, org.apache.http.Header[] headers,
				Throwable throwable, org.json.JSONArray errorResponse) {
			if (m_pResponseHandler != null) {
				m_pResponseHandler.OnFailure(YBRRequest.this);
			}

		};
	};

	// Initialization
	public YBRRequest(String argUrl, String argTag,
			YBRResponseHandler argHandler) {
		this.m_strUrl = argUrl;
		this.m_strRequestTag = argTag;
		m_pHttpClient = new AsyncHttpClient();
		m_pParams = new RequestParams();
		m_pHttpClient.setTimeout(20000);
		m_pResponseHandler = argHandler;

		// m_pParams.put("ver", AppConfigure.GetWebserviceVersion());
	}

	// Start the asynchronous request
	public void StartRequest() {
		Log.i("Request", "url=" + m_strUrl + " param=" + m_pParams.toString());
		m_pHttpClient.post(m_strUrl, m_pParams, pResponseHandler);
	}

	// Set the parameters for the request
	public void SetParamValue(String argValue, String argKey) {
		m_pParams.put(argKey, argValue);
	}

	// Set the image data parameter for the request
	public void AddImageData(File argImage, String argKey)
			throws FileNotFoundException {
		m_pParams.put(argKey, argImage);

	}

	// Set the image data parameter for the request
	public void AddImageData(File[] argImage, String argKey)
			throws FileNotFoundException {
		m_pParams.put(argKey, argImage);

	}

	// Cancel the request
	public void Cancel() {
		m_pHttpClient.cancelAllRequests(true);
	}
}
